package de.hach.manno;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import de.hach.manno.task.PutClubTask;
import de.hach.manno.webservice.Club;

public class ClubEditorActivity extends Activity implements OnClickListener,
		OnItemSelectedListener {
	private static final String TAG = "ClubEditorActivity";

	Spinner spinnerClubs;
	EditText editTextId, editTextName;
	Button saveButton;
	MannOData mannOData;
	Cursor cursor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.clubeditor);

		// Connect MannoDat
		mannOData = new MannOData(this);

		// Find views
		addClubsToSpinner();

		editTextId = (EditText) findViewById(R.id.idClubEditor);
		editTextName = (EditText) findViewById(R.id.nameClubEditor);

		saveButton = (Button) findViewById(R.id.buttonClubEditor);
		saveButton.setOnClickListener(this);

		Log.d(TAG, "onCreated");
	}

	public void addClubsToSpinner() {
		spinnerClubs = (Spinner) findViewById(R.id.spinnerClubEditor);
		cursor = mannOData.getClubNames();

		startManagingCursor(cursor);
		String[] columns = new String[] { MannOData.C_NAME };
		int[] to = new int[] { R.id.clubRowId };

		SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
				R.layout.club_row, cursor, columns, to);
		spinnerClubs.setAdapter(mAdapter);
		spinnerClubs.setOnItemSelectedListener(this);
	}

	// Called when Button is clicked
	public void onClick(View v) {
		if (v.getId() == (R.id.buttonClubEditor)) {
			Club club = new Club();
			club.setId(Integer.parseInt(editTextId.getText().toString()));
			club.setName(editTextName.getText().toString());
			new PutClubTask().execute(club);
		}
		Log.d(TAG, "onCLicked");
	}

	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		Log.d(TAG, parent + " " + view + " " + position + " " + id);
		cursor.moveToPosition(position);
		Log.d(TAG, cursor.getInt(0) + " " + cursor.getString(1));
		editTextId.setText("" + cursor.getInt(0));
		editTextName.setText(cursor.getString(1));
	}

	public void onNothingSelected(AdapterView<?> parent) {
		Log.d(TAG, "onNothignSelected");
		editTextId.setText("ID");
		editTextName.setText("NAME");
	}

}
